package cc.idoone.spring_boot_hello.jdbc;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
public class DataSourceConfiguration implements TransactionManagementConfigurer {

	@Resource(name = "jdbcManager")
	private PlatformTransactionManager txManager;

	@Bean
	@Primary
	@ConfigurationProperties("spring.datasource")
	public DataSource dataSource() {
		return new DruidDataSource();
		// return DruidDataSourceBuilder.create().build();
	}

	@Bean
	@Primary
	public JdbcTemplate jdbcTemplate(DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}

	@Bean(name = "jdbcManager")
	public PlatformTransactionManager txManager1(DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean
	public Object displayPlatformTransactionManager(PlatformTransactionManager jdbcManager) {
		System.out.println("事务管理器: " + jdbcManager.getClass().getName());
		return new Object();
	}

	/**
	 * 实现接口 TransactionManagementConfigurer 方法，其返回值代表在拥有多个事务管理器的情况下默认使用的事务管理器
	 */
	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return txManager;
	}
}